package edu.cebanc.spring.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import edu.cebanc.spring.bean.Account;
import edu.cebanc.spring.bean.Mascota;

@Controller
@RequestMapping(value="/mascotas")
public class MascotasSpringController {
	
	Map<String, Mascota> mascotas = new HashMap<String, Mascota>();
	
	@RequestMapping(method=RequestMethod.GET)
	public String cargarVistaPrincipal(Model model){
		
		List<Mascota> aux = new ArrayList<Mascota>();
		Set<String> keys = mascotas.keySet();
		Iterator<String> it = keys.iterator();

		while(it.hasNext()){
			Mascota a = mascotas.get(it.next());
			aux.add(a);
		}
		
		model.addAttribute("mascotas", aux);
		System.out.println("Tamanyo lista: "+aux.size());
		return "mascotasMain";
	}
	
	@RequestMapping(value="createForm", method=RequestMethod.GET)
	public String cargarVistaFormulario(Model model){
		
		Mascota mascota = new Mascota();
		model.addAttribute("nuevamascota", mascota);
		
		return "mascotasForm";
	}
	
	@RequestMapping(value="mascotas", method=RequestMethod.POST)
	public String gestionarFormulario(@Valid Mascota mascota, BindingResult result){
		
		if(result.hasErrors()){
			return "redirect:/mascotas/";
		}
		mascotas.put(mascota.getNombre(), mascota);
		
		return "redirect:/mascotas/";
	}
	
	
}
